package com.zbcz.erp.viewmodel

import androidx.lifecycle.ViewModel
import com.zbcz.erp.bean.BusinessAddBean
import com.zbcz.erp.bean.BusinessApplyBean
import com.zbcz.erp.network.ErpApi
import com.zbcz.erp.network.RetrofitManager
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File

open class BaseViewModel : ViewModel() {

    private val mApi = RetrofitManager.getRetrofit()?.create(ErpApi::class.java)

    suspend fun businessAdd(addBean: BusinessAddBean): String? {
        try {
            val result = mApi?.businessAdd(addBean)
            if (result?.code == 200) {
                return result.result
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }

    suspend fun businessApply(applyBean: BusinessApplyBean): Pair<String, Boolean> {
        try {
            val result = mApi?.businessApply(applyBean)
            if (result?.code == 200) {
                return Pair(result.message, true)
            } else {
                return Pair(result?.message ?: "", false)
            }
        } catch (e: Exception) {
            e.printStackTrace()
            return Pair("", false)
        }
        return Pair("", false)
    }

    suspend fun uploadImageSuspend(file: File): String? {
        val requestBody = RequestBody.create("*/*".toMediaTypeOrNull(), file)
        val filePart = MultipartBody.Part.createFormData("file", file.name, requestBody)
        val result = mApi?.uploadImage(filePart)
        if (result?.success == true) {
            return result.message
        }
        return null
    }
}